package top.fangw.common.mybatis.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import top.fangw.common.api.openfign.tenant.ITenantInfoServiceFeign;
import top.fangw.common.api.vo.TenantInfoVo;
import top.fangw.common.core.constant.BaseConstant;
import top.fangw.common.core.result.Result;
import top.fangw.common.mybatis.util.TableNameBuildUtil;
import top.fangw.common.mybatis.util.TenantInfoHelper;
import top.fangw.common.oauth.util.AccessTokenUtils;

/**
 * @description: 动态表名处理器
 * @author: fgw
 * @createDate: 2024/1/8
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class CustomizeTableNameHandler implements TableNameHandler {

    private final ITenantInfoServiceFeign tenantInfoServiceFeign;

    private final RedisTemplate<Object, Object> redisTemplate;

    @Override
    public String dynamicTableName(String sql, String tableName) {
        if (tableName.startsWith("g_tbl_")) {
            return tableName;
        }

        TenantInfoVo tenantInfoVo = TenantInfoHelper.get();
        String tenantId = AccessTokenUtils.getTenantId();
        if (tenantInfoVo == null && StrUtil.isNotBlank(tenantId)) {
            Result<TenantInfoVo> byTenantIdFeign = tenantInfoServiceFeign.getByTenantIdFeign(tenantId);
            if (byTenantIdFeign.getStatus()) {
                TenantInfoVo data = byTenantIdFeign.getData();
                if (BaseConstant.DATASOURCE_TYPE_DB.equals(data.getDatasourceType())) {
                    return TableNameBuildUtil.build(tableName, tenantId, true);
                } else if(BaseConstant.DATASOURCE_TYPE_TABLE.equals(data.getDatasourceType())){
                    return TableNameBuildUtil.build(tableName, tenantId, false);
                }
            }
        } else if (tenantInfoVo != null && StrUtil.isNotBlank(tenantInfoVo.getTenantId())) {
            TenantInfoVo data = (TenantInfoVo) redisTemplate.opsForValue().get("my:tenant:" + tenantInfoVo.getTenantId());
            if(data == null){
                return TableNameBuildUtil.build(tableName, tenantInfoVo.getTenantId(), true);
            }
            if (BaseConstant.DATASOURCE_TYPE_DB.equals(data.getDatasourceType())) {
                return TableNameBuildUtil.build(tableName, tenantInfoVo.getTenantId(), true);
            } else if(BaseConstant.DATASOURCE_TYPE_TABLE.equals(data.getDatasourceType())){
                return TableNameBuildUtil.build(tableName, tenantInfoVo.getTenantId(), false);
            }
        }

        return tableName;
    }
}
